package com.zhuliwei.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.service.UploadService;
import com.zhuliwei.utils.PathUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件上传接口实现类
 *
 * @author 朱力维
 * @time 2022/10/15 12:36
 **/
@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //判断文件类型

        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断
        if (!originalFilename.endsWith(".png")&&!originalFilename.endsWith(".jpg")&&!originalFilename.endsWith(".jpeg")
        &&!originalFilename.endsWith(".PNG")&&!originalFilename.endsWith(".JPG")&&!originalFilename.endsWith(".JPEG")
        ){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        // 如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img,filePath);
        return ResponseResult.okResult(url);
    }

    private String keyId;
    private String keySecret;
    //存储的空间名字
    private String bucketName;
    private String endpoint;

    // 阿里云oss
    private String uploadOss(MultipartFile imgFile, String filePath) {
        try {
            String url = null;
            //创建OSSClient实例。
            OSS ossClient = new OSSClient(endpoint, keyId, keySecret);
            //获取上传文件输入流
            InputStream inputStream = imgFile.getInputStream();
            //调用oss方法上传到阿里云
            //第一个参数：Bucket名称
            //第二个参数：上传到oss文件路径和文件名称
            //第三个参数：上传文件输入流
            ossClient.putObject(bucketName, filePath, inputStream);
            //把上传后把文件url返回
            //https://zlwblog.oss-cn-beijing.aliyuncs.com/01.jpg
            url = "https://" + bucketName + "." + endpoint + "/" + filePath;
            //关闭OSSClient
            ossClient.shutdown();
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "www";
    }
    // 七牛云oss
//    private String uploadOss(MultipartFile imgFile, String filePath) {
//        //构造一个带指定 Region 对象的配置类
//        Configuration cfg = new Configuration(Region.autoRegion());
//        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
////...其他参数参考类注释
//
//        UploadManager uploadManager = new UploadManager(cfg);
////...生成上传凭证，然后准备上传
//
////默认不指定key的情况下，以文件内容的hash值作为文件名
//        // 加“/”会在七牛云目录创建文件夹
//        String key = filePath;
//
//        try {
////            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
////            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
//
//            InputStream inputStream = imgFile.getInputStream();
//
//            Auth auth = Auth.create(accessKey, secretKey);
//            String upToken = auth.uploadToken(bucket);
//
//            try {
//                Response response = uploadManager.put(inputStream, key, upToken, null, null);
//                //解析上传成功的结果
//                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//                System.out.println(putRet.key);
//                System.out.println(putRet.hash);
//                return cdndomain+key;
//            } catch (QiniuException ex) {
//                Response r = ex.response;
//                System.err.println(r.toString());
//                try {
//                    System.err.println(r.bodyString());
//                } catch (QiniuException ex2) {
//                    //ignore
//                }
//            }
//        } catch (Exception ex) {
//            //ignore
//            ex.printStackTrace();
//        }
//        return "www";
//    }
}
